package com.example.gybicycle.common.util;

import com.example.gybicycle.entity.MenuMeta;
import com.example.gybicycle.entity.SysMenu;
import com.example.gybicycle.entity.SysMenuData;
import com.example.gybicycle.entity.SysMenu;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class TreeUtil {
    public static List<SysMenu> menuToTrees(List<SysMenu> treelist, Integer parentId) {
        List<SysMenu> list = treelist.stream()
                // 过滤父节点
                .filter(parent -> parent.getParentId().equals(parentId))
                .map(child -> {
                    child.setChildren(menuToTrees(treelist,Integer.valueOf(child.getId())));
                    return child;
                }).collect(Collectors.toList());
        list.stream().sorted(Comparator.comparing(SysMenu::getSort));
        return list;
    }
  /*  public static List<SysMenu> menuToTree(List<SysMenu> treelist, Integer parentId) {
        List<SysMenuData> list = treelist.stream()
                // 过滤父节点
                .filter(parent -> parent.getPid().equals(parentId))
                .map(child -> {
                    child.setChildren(menuToTree(treelist,Integer.valueOf(child.getId())));
                    return child;
                }).collect(Collectors.toList());
        list.stream().sorted(Comparator.comparing(SysMenu::getSort));
        return list;
    }*/
    public static List<SysMenuData> menuToTree(List<SysMenuData> treelist, Integer parentId) {
        List<SysMenuData> list = treelist.stream()
                // 过滤父节点
                .filter(parent -> parent.getParentId().equals(parentId))
                .map(child -> {
                    child.setChildren(menuToTree(treelist,child.getId()));
                    return child;
                }).collect(Collectors.toList());
         list.stream().sorted(Comparator.comparing(SysMenuData::getSort));
        return list;
    }

    public static  List<SysMenuData> menuToTree(List<SysMenu> treelist){
        List<SysMenuData> menuDataList=new ArrayList<>();
        for(SysMenu menu:treelist){
            SysMenuData data=new SysMenuData();
            BeanUtils.copyProperties(menu,data);
            MenuMeta menuMeta=new MenuMeta();
            BeanUtils.copyProperties(menu,menuMeta);
            menuMeta.setRoles(Arrays.asList("ADMIN"));
            data.setId(Integer.valueOf(menu.getId()));
            data.setMeta(menuMeta);
            menuDataList.add(data);
        }
        menuDataList=menuToTree(menuDataList,0);
        return menuDataList;
    }
}
